<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" width="50%" />
          <el-table-column label="姓名" prop="username" />
          <!-- 显示员工头像 -->
          <el-table-column label="员工头像">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <!-- 查询参数传值:获取值this.$route.query -->
              <!-- <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?userId=${row.id}`)"
              >查看</el-button> -->
              <!-- 路径参数传值:获取值this.$route.params -->
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hdel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="添加员工" :visible.sync="showDialog" width="50%">
        <addorEdit
          v-if="showDialog"
          @success="hSuccess"
          @close="showDialog = false"
        />
      </el-dialog>
      <!-- 生成二维码的图片 -->
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog" width="50%">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="AssignRoleDialog">
        <assignRole
          v-if="AssignRoleDialog"
          :cur-id="curId"
          @success="AssignRoleDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { delEmployees, getEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addorEdit from '@/views/employees/empDialog.vue'
import assignRole from './assignRole.vue'
// 定义一个对象来接收数据
// const hireType = {} // {1:'正式',2:'非正式'}
// 遍历数据
// employeesEnum.hireType.forEach(item => {
//   // 得到{1:'正式',2:'非正式'}
//   hireType[item.id] = item.value
// })
// 使用reduce来处理数据
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
import QRCode from 'qrcode'
// console.log(hireType)
export default {
  name: 'VueHrEmployees',
  components: {
    addorEdit,
    assignRole
  },
  data() {
    return {
      curId: '',
      AssignRoleDialog: false, // 控制分配角色弹层
      showCodeDialog: false, // 显示二维码图片
      list: [], // 员工列表
      page: 1, // 页码值
      size: 10, // 每页的数量
      total: 0, // 总条数
      showDialog: false
    }
  },

  created() {
    this.loadEmployees()
  },

  methods: {
    hAssignRole(id) {
      this.curId = id
      this.AssignRoleDialog = true
    },
    // 显示二维码图片
    showCode(url) {
      // 弹出弹窗
      this.showCodeDialog = true
      if (url) {
        // dom更新是异步的
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请传入正确的图片')
      }
    },
    // 导出员工
    exportExcel() {
      import('@/vendor/Export2Excel').then((excel) => {
        // 获取后台的数据，通过js进行对数据处理
        const { tHeader, data } = this.transZhkeyToExcel(this.list)
        // excel指的模块对象，那么可以使用这个模块对象去调用这个模块里面的函数或者变量 excel.函数名()
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhkeyToExcel(list) {
      // 中引文的映射对象
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }

      // 生成标头
      const one = list[0]
      // 进行遍历，如果有数据||undefined
      if (!one) return
      // 有数据获取表头
      const tHeader = Object.keys(one).map((item) => mapInfo[item])
      // 获取数据
      const data = list.map((item) => Object.values(item))

      return { tHeader, data }
    },
    hSuccess() {
      // 添加数据到最大的一页
      this.total++
      // 计算最大的页码值
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      // 重新渲染
      this.loadEmployees()
      // 关闭弹窗
      this.showDialog = false
    },
    // 格式化数据的函数
    formatData(id) {
      return hireType[id] || '未知'
    },
    // 删除员工
    hdel(id) {
      // console.log(id)
      this.$confirm('您确定要删除此员工嘛?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 发送请求进行删除
          const res = await delEmployees(id)
          if (res.code === 10000) {
            this.$message.success('删除成功!')
            // 判断当前页数是否剩下1条
            if (this.list.length === 1) {
              // 页面数减1
              this.page--
              // 如果页数小与0则把页面重置为1
              if (this.page <= 0) {
                this.page = 1
              }
            }
            // 重新渲染
            this.loadEmployees()
          }
        })
        .catch(() => {
          this.$message('已取消删除')
        })
    },
    // 获取员工列表
    async loadEmployees() {
      try {
        // 发送请求
        const res = await getEmployees({ page: this.page, size: this.size })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        // 成功
        this.$message.success(res.message)
        // 赋值
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error)
      }
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      // 重新渲染
      this.loadEmployees()
    }
  }
}
</script>
